package com.yum.ms.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yum.ms.aop.RedisCache;
import com.yum.ms.entity.Goods;
import com.yum.ms.entity.vo.GoodsVO;
import com.yum.ms.mapper.GoodsMapper;
import com.yum.ms.service.IGoodsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Yum
 * @since 2022-02-16
 */
@Service
@Slf4j
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements IGoodsService {

    @Autowired
    private GoodsMapper goodsMapper;

    @RedisCache
    @Override
    public List<GoodsVO> selectGoodsVOList() {
        return goodsMapper.selectGoodsVOList();
    }

    @Override
    public GoodsVO selectGoodsVOById(Long goodsId) {
        GoodsVO goodsVO = goodsMapper.selectGoodsVOById(goodsId);
        return goodsVO;
    }

    public Map info(GoodsVO goodsVO) {
        // 时间格式化
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime startDate = goodsVO.getStartDate();
        LocalDateTime endDate = goodsVO.getEndDate();
        LocalDateTime nowDate = LocalDateTime.now();
        //第二种(参数一开始时间，参数二结束时间)
        Duration duration = Duration.between(nowDate,startDate);
        long days = duration.toDays(); //相差的天数
        long hours = duration.toHours();//相差的小时数
        long minutes = duration.toMinutes();//相差的分钟数
        long millis = duration.toMillis();//相差毫秒数
        long nanos = duration.toNanos();//相差的纳秒数
        // 秒杀状态
        String status;
        // 秒杀倒计时
        long remainSeconds = 0;
        if(nowDate.isBefore(startDate)) {
            status = "未开始";
            remainSeconds = millis / 1000;
        }else {
            status = nowDate.isAfter(endDate) ? "已结束" : "已开始";
            remainSeconds = millis / 1000;
        }
//        log.info("开始时间:{},秒杀状态:{},秒杀倒计时:{}秒",startDate.format(formatter),status,remainSeconds);
        HashMap<String, Object> map = new HashMap<>();
        map.put("startDate",startDate.format(formatter));
        map.put("status",status);
        map.put("remainSeconds",remainSeconds);
        return map;
    }
}
